Skip to content

Conversation

Caellian
Copy link
Contributor

@Caellian Caellian commented Sep 13, 2025

References are turned into pointers in C ABI, but C++ compiler treats them as NonNull. Allowing null values is invalid 100% of the time, and causes segfaults in cases like:

void my_assigner(std::string& to_value) {
  // C++ doesn't allow asserting `to_value != nullptr` because it's impossible by design
  to_value = std::string("Hello there");
}

C++ reference:

A reference is required to be initialized to refer to a valid object or function: see reference initialization.

@Caellian
Copy link
Contributor Author

r? @emilio

@Caellian
Copy link
Contributor Author

Caellian commented Sep 13, 2025

I don't like how using NonNull erases is_const though. It'd be ideal for postprocessing if bindgen could generate type ConstNonNull<T> = ::std::ptr::NonNull<T> alias at the beginning of the file to communicate the original reference was const. Is this allowed? If so I'd like to add it.

Copy link
Contributor

@emilio emilio left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code wise looks fine but I'm not terribly convinced we should do this by default:

  • Losing the const-ness seems really really unfortunate.
  • It makes calling the function more complicated (specially if you can't use NonNull::from_ref / NonNull::from_mut).

FWIW passing a null pointer might be UB anyways even if the function doesn't take a reference (e.g. if the C++ function dereferences it without checking), so this only gives you a somewhat minor improvement, which IMO is not worth losing the const-ness.

I'd be fine adding an opt-in so that people can use this if the trade-off makes sense for them tho. Might be worth making the default after a bit, if people find it useful.

@Caellian Caellian force-pushed the main branch 4 times, most recently from 987a56f to 28120b0 Compare September 18, 2025 19:26
- Make feature disabled by default until usability concerns are resolved.
- Add test for --nonnull-references argument

Signed-off-by: Tin Švagelj <[email protected]>
@emilio emilio enabled auto-merge October 2, 2025 15:24
@emilio emilio added this pull request to the merge queue Oct 2, 2025
Merged via the queue into rust-lang:main with commit ac0fa3b Oct 2, 2025
51 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants